package com.cskaoyan.controller.authController;

import com.cskaoyan.config.MallToken;
import com.cskaoyan.exceptionJY.*;
import com.cskaoyan.model.bo.LoginBo;
import com.cskaoyan.model.bo.systembo.CodeBo;
import com.cskaoyan.model.bo.systembo.RegisterBo;
import com.cskaoyan.model.bo.systembo.ResetBo;
import com.cskaoyan.model.vo.BaseRespVo;
import com.cskaoyan.model.vo.systemvo.RegisterVo;
import com.cskaoyan.model.vo.systemvo.WxLoginVo;
import com.cskaoyan.service.AuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WxAuthController {

    @Autowired
    AuthService authService;

    @RequestMapping("/wx/auth/login")
    public BaseRespVo login(@RequestBody LoginBo loginBo) throws WrongPasswordException {
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new MallToken(loginBo.getUsername(),loginBo.getPassword(),"wx"));
        } catch (AuthenticationException e) {
            //验证未通过
            throw new WrongPasswordException();
        }
        //验证通过
        WxLoginVo wxLoginVo = authService.login(loginBo);
        return BaseRespVo.ok(wxLoginVo);
    }

    @RequestMapping("wx/auth/logout")
    public BaseRespVo logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }

    @RequestMapping("/wx/auth/regCaptcha")
    public BaseRespVo regCaptcha(@RequestBody CodeBo codeBo) throws PhoneNumberException {
        authService.regCaptcha(codeBo);
        return BaseRespVo.ok();
    }

    @RequestMapping("/wx/auth/register")
    public BaseRespVo register(@RequestBody RegisterBo registerBo) throws Exception {

        RegisterVo registerVo = authService.register(registerBo);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new MallToken(registerBo.getUsername(),registerBo.getPassword(),"wx"));
        } catch (AuthenticationException e) {
            //验证未通过
            throw new WrongPasswordException();
        }
        return BaseRespVo.ok(registerVo);
    }

    @RequestMapping("/wx/auth/reset")
    public BaseRespVo reset(@RequestBody ResetBo resetBo) throws CodeErrorException, PhoneNumberNotExitsException {
        authService.reset(resetBo);
        return BaseRespVo.ok();
    }


}
